#include "EventServer.h"

#include "DataManager.h"
#include "EventExecuter.h"
#include "EventObject.h"
#include "NetworkObject.h"

#include <libintl.h>
#include <stdio.h>
#include <stdlib.h>

#define _(String) gettext(String)

struct _EventServer
{
	EventObject    parent_instance;
	EventExecuter *executer;
	DataManager   *data_manager;
	NetworkObject *net_obj;
};

static void
event_server_finalize(EventServer *self)
{
	event_object_unref(self->executer);
	event_object_unref(self->data_manager);
	event_object_unref(self->net_obj);
}

EventServer *
event_server_new(void)
{
	EventServer *object = MALLOC_NEW(EventServer);

	event_object_init(EVENT_OBJECT(object));
	event_object_set_finalize(object, FINALIZE(event_server_finalize));

	object->data_manager = data_manager_new();
	object->executer     = event_executer_new();
	object->net_obj	     = network_object_new();

	network_object_signal_connect_accept(
		object->net_obj, NETWORK_CALLBACK(event_executer_run_node),
		EVENT_OBJECT(object->executer));

	return object;
}

void
event_server_set_runtime_path(EventServer *self, const char *path)
{
	return_if_fail(self != NULL && path != NULL, event_server_runtime_path);
	data_manager_set_base_path(self->data_manager, path);
}

int
event_server_run(EventServer *self)
{
	DataManagerRet d_status;
	int	       status = 1;

	d_status = data_manager_init(self->data_manager);
	if (d_status != DATA_MANAGER_SUCCESS) {
		printf(_("Error in run serverObject. (d_status: %d)\n"),
		       d_status);
		return 1;
	}

	event_executer_connect_data_manager(self->executer, self->data_manager);
	event_executer_connect_network_object(self->executer, self->net_obj);
	network_object_init(self->net_obj);
	/*
        while (1) {
                q_node = network_object_accept(self->net_obj);
                if (!q_node)
                        return 0;
                event_executer_add_task(self->executer, q_node);
        }*/

	while (status)
		status = network_object_loop_wait(self->net_obj);
	return 0;
}